from flask import url_for
from app.constants import UEDITOR_UPLOAD_PATH, UEDITOR_UPLOAD_BASE
from app.models import Attachment
from app import db

import time
import os
import random
import hashlib
import string

''' 随机生成指定长度字符串 '''
def create_nonce_str(length = 6):
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return "".join(random.sample(chars, length))

''' md5加密 '''
def md5(str):
    md5 = hashlib.md5()
    md5.update(str.encode('utf-8'))
    return md5.hexdigest()

''' 创建用户密码 '''
def create_password(password, salt):
    return md5(md5(password) + salt)


''' 生成加密文件名 '''
def _random_filename(rawfilename):
    
    letters = string.ascii_letters
    random_filename = str(time.time()) + "".join(random.sample(letters,5))
    filename = hashlib.md5(random_filename.encode('utf-8')).hexdigest()
    subffix = os.path.splitext(rawfilename)[-1]
    return filename + subffix

''' 图片上传 '''
def upload_image(request, file_name='upfile'):
    image = request.files.get(file_name)
    filename = image.filename
    result = {
        'state': 'SUCCESS',
        'url': '',
        'title': '',
        'original': ''
    }
    # 判断表中是否存在图片
    attachment = Attachment.query.filter_by(filename=filename).first()
    if attachment:
        result['url'] = attachment.url
        result['title'] = attachment.name,
        result['original'] = filename
    else:
        save_filename = _random_filename(filename)
        
        file_dir = time.strftime("%Y%m%d",time.localtime())
        full_dir = os.path.join(UEDITOR_UPLOAD_PATH, file_dir)
        if not os.path.isdir(full_dir):
            os.mkdir(full_dir)
        image.save(os.path.join(full_dir, save_filename))
        result['url'] = url_for('upload.files', dirname = file_dir, filename= save_filename)
        result['title'] = save_filename,
        result['original'] = image.filename
        # 添加到附件表中
        attachment = Attachment(name=result['title'], filename=result['original'], url=result['url'])
        db.session.add(attachment)
        db.session.commit()

    return result

''' 删除图片 '''
def delete_image(url):
    os.unlink(UEDITOR_UPLOAD_BASE + url)
